package com.autonavi.yunda.yunji.controller.request;

import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.enums.EngineType;
import com.autonavi.yunda.yunji.core.enums.InterfaceStatus;
import com.autonavi.yunda.yunji.core.enums.Method;
import com.autonavi.yunda.yunji.core.model.dto.InterfaceConfigDTO;
import com.autonavi.yunda.yunji.core.model.vo.InterfaceData;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.Data;
import org.apache.logging.log4j.util.Strings;

import javax.validation.constraints.NotNull;

/**
 * @author cizhong.wcs
 * @date 2022/8/10 14:56
 */
@Data
public class InterfaceConfigUpdateRequest {
    @NotNull
    private Long id;
    private String name;
    private String description;
    private Method method;
    private EngineType engineType;
    private String engineData;
    private String extraData;
    private Object response;
    private String operator;

    public UpdateWrapper<InterfaceConfigDTO> fetchUpdateWrapper(InterfaceConfigDTO oldDto, String operator) {
        UpdateWrapper<InterfaceConfigDTO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        if (Strings.isNotBlank(name)) {
            updateWrapper.set("name", name);
        }
        if (Strings.isNotBlank(description)) {
            updateWrapper.set("description", description);
        }
        if (method != null) {
            updateWrapper.set("method", method);
        }
        if (engineType != null) {
            updateWrapper.set("engine_type", engineType);
        }
        if (Strings.isNotBlank(engineData)) {
            if (oldDto.getStatus().equals(InterfaceStatus.TEST_SUCCESS) && !oldDto.getEngineData().equals(engineData)) {
                updateWrapper.set("status", InterfaceStatus.INIT);
            }
            updateWrapper.set("engine_data", engineData);
        }
        if (Strings.isNotBlank(extraData)) {
            updateWrapper.set("extra_data", extraData);
        }
        if (response != null) {
            InterfaceData interfaceData = oldDto.getInterfaceData();
            interfaceData.response = response;
            updateWrapper.set("interface_data", JsonUtils.toString(interfaceData));
        }
        if (Strings.isNotBlank(operator)) {
            updateWrapper.set("update_user", operator);
        }
        return updateWrapper;
    }
}
